<template>
	<view class="login-container">
		<view class="login-header">
			<text class="login-title">登录后更精彩</text>
		</view>
		
		<view class="login-tabs">
			<view class="tab-item" :class="{ active: loginType === 'phone' }" @click="switchTab('phone')">
				<text>手机密码登录</text>
			</view>
			<view class="tab-item" :class="{ active: loginType === 'code' }" @click="switchTab('code')">
				<text>验证码登录</text>
			</view>
		</view>
		
		<view class="login-form">
			<!-- 手机号输入框 -->
			<view class="input-group">
				<view class="country-code">
					<text>+86</text>
					<text class="arrow-down">▼</text>
				</view>
				<input class="input-field" type="number" placeholder="请输入您的手机号" placeholder-class="placeholder" v-model="phone" @blur="validatePhone" />
			</view>
			
			<!-- 手机号错误提示 -->
			<view class="phone-tip" v-if="phoneError">
				<text>请输入正确的手机号格式</text>
			</view>
			
			<!-- 密码输入框 -->
			<view class="input-group" v-if="loginType === 'phone'">
				<view class="input-label">
					<text>密码</text>
				</view>
				<input class="input-field" type="text" :password="!showPassword" placeholder="请输入您的密码" placeholder-class="placeholder" v-model="password" />
				<view class="password-icon" @click="togglePasswordVisibility">
					<text class="iconfont">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
				</view>
			</view>
			
			<!-- 验证码输入框 -->
			<view class="input-group" v-if="loginType === 'code'">
				<view class="input-label">
					<text>验证码</text>
				</view>
				<input class="input-field" type="number" placeholder="请输入验证码" placeholder-class="placeholder" v-model="verificationCode" />
				<view class="code-button" :class="{ disabled: codeButtonDisabled }" @click="getVerificationCode">
					<text>{{ codeButtonText }}</text>
				</view>
			</view>
			
			<!-- 登录按钮 -->
			<view class="login-button" @click="login">
				<text>登录</text>
			</view>
			
			<!-- 底部链接 -->
			<view class="bottom-links">
				<view class="link right" @click="goToRegister">
					<text>注册新用户</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import authManager from '@/utils/auth.js'
import Validator, { VALIDATION_RULES } from '@/utils/validator.js'
import { userAPI, authAPI } from '@/utils/api.js'
import { showSuccess, showError, showErrorFromObject } from '@/utils/toast.js'

export default {
	data() {
		return {
			loginType: 'phone', // 'phone' 或 'code'
			phone: '',
			password: '',
			verificationCode: '',
			showPassword: false,
			codeButtonText: '获取验证码',
			codeButtonDisabled: false,
			countdown: 0,
			phoneError: false
		}
	},
	methods: {
		switchTab(type) {
			this.loginType = type;
			// 切换时清空表单
			this.clearForm();
		},
		
		togglePasswordVisibility() {
			this.showPassword = !this.showPassword;
		},
		
		goToRegister() {
			uni.navigateTo({
				url: '/pages/register/register'
			});
		},
		
		clearForm() {
			this.password = '';
			this.verificationCode = '';
		},
		
		/**
		 * 验证手机号格式
		 */
		validatePhone() {
			this.phoneError = !Validator.isValidPhone(this.phone) && this.phone !== '';
		},
		
		/**
		 * 获取验证码
		 */
		async getVerificationCode() {
			// 验证手机号
			if (!Validator.isValidPhone(this.phone)) {
				showError('请输入正确的手机号');
				return;
			}
			
			try {
				await userAPI.sendVerificationCode(this.phone, 'login');
				
				showSuccess('验证码已发送');
				
				// 开始倒计时
				this.startCountdown();
				
			} catch (error) {
				console.error('发送验证码失败:', error);
				showErrorFromObject(error, '发送验证码失败');
			}
		},
		
		/**
		 * 开始倒计时
		 */
		startCountdown() {
			this.countdown = 60;
			this.codeButtonDisabled = true;
			this.codeButtonText = `${this.countdown}s后重发`;
			
			const timer = setInterval(() => {
				this.countdown--;
				this.codeButtonText = `${this.countdown}s后重发`;
				
				if (this.countdown <= 0) {
					clearInterval(timer);
					this.codeButtonDisabled = false;
					this.codeButtonText = '获取验证码';
				}
			}, 1000);
		},
		
		/**
		 * 表单验证
		 */
		validateForm() {
			const formData = {
				account: this.phone,
				password: this.password,
				phone: this.phone,
				verificationCode: this.verificationCode
			};
			
			let rules;
			if (this.loginType === 'phone') {
				rules = VALIDATION_RULES.LOGIN;
				formData.account = this.phone; // 使用手机号作为账号
			} else {
				rules = VALIDATION_RULES.LOGIN_CODE;
			}
			
			const result = Validator.validateForm(formData, rules);
			
			if (!result.isValid) {
				showError(result.firstError);
				return false;
			}
			
			return true;
		},
		
		/**
		 * 登录处理
		 */
		async login() {
			// 表单验证
			if (!this.validateForm()) {
				return;
			}
			
			this.loading = true;
			
			try {
				let loginData;
				
				if (this.loginType === 'phone') {
					// 密码登录 - 使用后端期望的格式
					loginData = {
						phone: this.phone,
						password: this.password
					};
				} else {
					// 验证码登录 - 直接使用验证码登录接口
					loginData = {
						phone: this.phone,
						code: this.verificationCode
					};
					
					// 调用验证码登录接口
					const result = await authAPI.loginByCode(loginData);
					
					if (result.code === 200 && result.data) {
						// 验证码登录成功，保存令牌信息
						if (result.data.token) {
							uni.setStorageSync('asurada_user_token', result.data.token);
							uni.setStorageSync('asurada_login_time', Date.now());
						}
						
						// 保存用户信息
						if (result.data.userInfo) {
							uni.setStorageSync('asurada_user_info', result.data.userInfo);
						}
						
						// 更新认证管理器状态
						authManager.init();
						
						showSuccess('登录成功');
						
						// 延迟跳转，让用户看到成功提示
						setTimeout(() => {
							// 跳转到主界面
							uni.reLaunch({
								url: '/pages/index/index',
								success: () => {
									// 通知主界面刷新用户信息
									uni.$emit('userLoginSuccess');
								}
							});
						}, 1500);
					} else {
						showError(result.message || '登录失败');
					}
					
					return;
				}
				
				// 密码登录调用两步登录接口
				const result = await authManager.login(loginData);
				
				if (result.code === 200) {
					showSuccess('登录成功');
					
					// 延迟跳转，让用户看到成功提示
					setTimeout(() => {
						// 跳转到主界面
						uni.reLaunch({
							url: '/pages/index/index',
							success: () => {
								// 通知主界面刷新用户信息
								uni.$emit('userLoginSuccess');
							}
						});
					}, 1500);
				}
				
			} catch (error) {
				console.error('登录失败:', error);
				
				// 根据错误类型显示不同的提示
				if (error.message) {
					// 后端返回的具体错误信息
					showError(error.message);
				} else {
					// 网络或其他错误
					showErrorFromObject(error, '登录失败，请稍后重试');
				}
			} finally {
				this.loading = false;
			}
		}
	},
	
	onLoad() {
		// 检查是否已经登录
		if (authManager.isAuthenticated()) {
			// 已登录，直接跳转到首页
			uni.switchTab({
				url: '/pages/index/index'
			});
		}
	},
	
	watch: {
		// 监听手机号变化，实时验证
		phone() {
			if (this.phone) {
				this.validatePhone();
			} else {
				this.phoneError = false;
			}
		}
	}
}
</script>

<style>
.login-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #1e2433;
	padding: 0 30rpx;
}

.login-header {
	margin-top: 150rpx;
	margin-bottom: 80rpx;
}

.login-title {
	font-size: 48rpx;
	color: #ffffff;
	font-weight: bold;
}

.login-tabs {
	display: flex;
	margin-bottom: 60rpx;
}

.tab-item {
	margin-right: 40rpx;
	padding-bottom: 10rpx;
	color: #8a8a9a;
	font-size: 32rpx;
}

.tab-item.active {
	color: #ffffff;
	border-bottom: 4rpx solid #ffffff;
}

.input-group {
	display: flex;
	align-items: center;
	background-color: #2a304d;
	border-radius: 50rpx;
	padding: 20rpx 30rpx;
	margin-bottom: 30rpx;
	height: 90rpx;
}

.country-code {
	display: flex;
	align-items: center;
	color: #ffffff;
	margin-right: 20rpx;
	font-size: 32rpx;
}

.arrow-down {
	font-size: 20rpx;
	margin-left: 10rpx;
	color: #8a8a9a;
}

.input-label {
	color: #ffffff;
	font-size: 32rpx;
	margin-right: 20rpx;
	width: 120rpx;
}

.input-field {
	flex: 1;
	color: #ffffff;
	font-size: 32rpx;
}

.placeholder {
	color: #8a8a9a;
}

.password-icon {
	color: #8a8a9a;
	font-size: 40rpx;
}

.code-button {
	color: #ffffff;
	font-size: 28rpx;
	background-color: #3a4366;
	padding: 10rpx 20rpx;
	border-radius: 30rpx;
	transition: background-color 0.3s;
}

.code-button.disabled {
	background-color: #2a2a2a;
	color: #666666;
}

.login-button {
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #4e5eff;
	border-radius: 50rpx;
	height: 90rpx;
	margin-top: 60rpx;
	color: #ffffff;
	font-size: 32rpx;
}

.bottom-links {
	display: flex;
	justify-content: flex-end;
	margin-top: 40rpx;
}

.link {
	color: #8a8a9a;
	font-size: 28rpx;
}

.phone-tip {
	color: #ff4a4a;
	font-size: 24rpx;
	margin-top: -10rpx;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
}
</style>
